/**
 * @file skoll.tools.loading.js
 * @author Alejandro Dario Simi
 * @date $Date: 2014-05-04 01:33:52 +0000 (Sun, 04 May 2014) $
 *
 * $Id: skoll.tools.loading.js 111 2014-05-04 01:33:52Z daemonraco@gmail.com $
 * $URL: http://wcomix.googlecode.com/svn/trunk/skins/Skoll/js/skoll.tools.loading.js $
 */

/**
 * Skoll loading screen.
 */
Skoll.tools.Loading = {
	//
	// Protected properties.
	_closed: false,
	_countPosition: 0,
	_countTotal: 0,
	_latency: 200,
	//
	// Public methods.
	increaseCount: function(increment) {
		if (typeof increment == "undefined") {
			increment = 1;
		}

		Skoll.tools.Loading.setCount(Skoll.tools.Loading._countPosition + increment);
	},
	setCount: function(count) {
		if (!Skoll.tools.Loading._closed && Skoll.tools.Loading._countTotal > 0 && count <= Skoll.tools.Loading._countTotal) {
			Skoll.tools.Loading._countPosition = count;
			Skoll.tools.Loading._setCountText();
		} else {
			Skoll.tools.log("Skoll.tools.Loading.setCount(): Count is at its limit");
		}
	},
	setLatency: function(latency) {
		Skoll.tools.Loading._latency = latency;
	},
	setCountTotal: function(total) {
		if (!Skoll.tools.Loading._closed && Skoll.tools.Loading._countTotal > 0 && total > 0) {
			Skoll.tools.Loading._countTotal = total;
			Skoll.tools.Loading._setCountText();
		}
	},
	start: function(startDelay) {
		Skoll.tools.Loading.stop();

		var delay = Skoll.tools.Loading._latency;

		if (typeof startDelay !== "undefined") {
			delay = startDelay;
		}

		Skoll.tools.Loading._closed = false;
		setTimeout(function() {
			Skoll.tools.Loading._createScreen(false);
		}, delay);
	},
	startCount: function(total) {
		Skoll.tools.Loading.stop();
		Skoll.tools.Loading._closed = false;
		Skoll.tools.Loading._countTotal = total;
		Skoll.tools.Loading.setCount(0);
		Skoll.tools.Loading._createScreen(true);
	},
	stop: function() {
		$("#LoadingScreen").remove();
		Skoll.tools.Loading._countTotal = 0;
		Skoll.tools.Loading._closed = true;
	},
	//
	// Protected methods.
	_createScreen: function(hasCount) {
		if (!Skoll.tools.Loading._closed) {
			var countHTML = hasCount && Skoll.tools.Loading._countTotal > 0 ? '<span class="Countdown"></span>' : '';
			$("body").append('<div id="LoadingScreen"><div class="MessageFrame"><img src="' + SKIN_URI + '/images/wcomix-loading-256px.gif" alt="Loading..."/>' + countHTML + '</div></div>');
			Skoll.tools.Loading._setCountText();
		}
	},
	_setCountText: function() {
		if (!Skoll.tools.Loading._closed) {
			$("#LoadingScreen .Countdown").text(Skoll.tools.Loading._countPosition + '/' + Skoll.tools.Loading._countTotal);
		}
	}
};